<template>
  <keep-alive>
    <a-row style="margin-top: 10px" justify="center"  class="article">
      <a-col span="24" :md="{span : 19}" :xl="{span : 17}">
        <a-flex style="margin-bottom: 5px" wrap="wrap" :gap="10"  justify="flex-start" align="center">
          <a-col>
            <a-space>
              <a-select
                  v-model:value="queryFrom.typeId"
                  style="width: 120px"
                  :field-names="{ label: 'name', value: 'id', options: 'children' }"
                  :options="typeList"
              >
                <template #suffixIcon><smile-outlined class="ant-select-suffix" /></template>
              </a-select>
            </a-space>
          </a-col>
          <a-col flex="auto">
            <a-input-search v-model:value="queryFrom.searchKey" placeholder="关键字" :loading="loading" />
          </a-col>
          <a-col>
            <a-button @click="gotoAddArticle(null)" type="primary">发布讨论</a-button>
          </a-col>
        </a-flex>
<!--        <a-row  :gap="10" gutter="16" justify="start" style="margin-bottom: 15px;">-->
<!--          <a-col>-->
<!--            <a-space>-->
<!--              <a-select-->
<!--                  v-model:value="queryFrom.typeId"-->
<!--                  style="width: 120px"-->
<!--                  :field-names="{ label: 'name', value: 'id', options: 'children' }"-->
<!--                  :options="typeList"-->
<!--              >-->
<!--                <template #suffixIcon><smile-outlined class="ant-select-suffix" /></template>-->
<!--              </a-select>-->
<!--            </a-space>-->
<!--          </a-col>-->
<!--          <a-col flex="auto">-->
<!--            <a-input-search v-model:value="queryFrom.searchKey" placeholder="关键字" :loading="loading" />-->
<!--          </a-col>-->
<!--          <a-col>-->
<!--            <a-button @click="gotoAddArticle(null)" type="primary">发布讨论</a-button>-->
<!--          </a-col>-->
<!--        </a-row>-->
        <a-card class="card" size="small" title="文章列表" >

          <template #extra>
            <a-checkbox v-model:checked="queryFrom.star">收藏</a-checkbox>
            <a-checkbox v-if="queryFrom.userId == null || queryFrom.userId == ''" v-model:checked="queryFrom.me">我的</a-checkbox>
            <a-radio-group size="small" v-model:value="queryFrom.seq">
              <a-radio-button :value="1">最新</a-radio-button>
              <a-radio-button :value="2">最热</a-radio-button>
            </a-radio-group>

          </template>
          <a-list  item-layout="vertical" size="large" :pagination="false" :data-source="listData">
            <template #loadMore>
              <div

                  :style="{ textAlign: 'center', marginTop: '12px', height: '32px', lineHeight: '32px' }"
              >
                <a-button  v-if="more && !loading"  @click="onLoadMore">加载更多</a-button>
                <span v-else-if="loading">加载中...</span>
                <span v-else>到底了...</span>
              </div>
            </template>
            <template #renderItem="{ item }">
              <a-badge-ribbon v-if="item.isTop" text="置顶" color="pink">
                <a-skeleton avatar :title="false" :loading="loading" active>
                  <a-list-item :key="item.id">
                    <template  #actions>
                    <span v-if="item.collection" :style="{color : token.colorSuccess}"  style="cursor: pointer">
                      <component @click="toCollection(item)" :is="StarOutlined" style="margin-right: 8px" />
                      {{ item.collectionNum || 0 }}
                    </span >
                      <span v-else style="cursor: pointer">
                        <component @click="toCollection(item)" :is="StarOutlined" style="margin-right: 8px" />
                        {{ item.collectionNum || 0 }}
                    </span >

                      <span v-if="item.thumbs" :style="{color : token.colorSuccess}"  style="cursor: pointer">
                        <component  style="margin-right: 8px;"  @click="toThumbs(item)"  :is="LikeOutlined"  />
                        {{ item.thumbsNum || 0 }}
                    </span>
                      <span v-else  style="cursor: pointer">
                        <component  style="margin-right: 8px;"  @click="toThumbs(item)"  :is="LikeOutlined"  />
                        {{ item.thumbsNum || 0 }}
                    </span>

                      <span>
                        <component :is="MessageOutlined" style="margin-right: 8px" />
                        {{ item.articleCommentNum || 0 }}
                    </span>

                      <span>
                        <component :is="MessageOutlined" style="margin-right: 8px" />
                        {{item.createTime}}
                      </span>
                      <span v-if="user.id == item.userId">
                     <a-dropdown>
                        <a class="ant-dropdown-link" @click.prevent>
                          more
                          <DownOutlined />
                        </a>
                        <template #overlay>
                          <a-menu>
                            <a-menu-item >
                              <a-popconfirm
                                  title="删除后不可恢复，确定删除？"
                                  ok-text="是"
                                  cancel-text="否"
                                  @confirm="delArticle(item.id)">
                              <a href="#">删除</a>
                            </a-popconfirm>
                            </a-menu-item>
                            <a-menu-item @click="gotoAddArticle(item.id)">
                              <a href="javascript:;">编辑</a>
                            </a-menu-item>
                          </a-menu>
                        </template>
                      </a-dropdown>
                  </span>
                    </template>
                    <template v-if="!isMobile.value" #extra>
                      <img
                          width="272"
                          height="150"
                          style="border-radius: 5px;cursor: pointer"
                          @click="gotoArticle(item.id)"
                          alt="logo"
                          :src="item.articleCover"

                      />
                    </template>
                    <a-list-item-meta description="">
                      <template #title>
                        <a @click="gotoArticle(item.id)" >{{ item.articleTitle }}</a>
                      </template>
                      <template #avatar><a-avatar  style="cursor: pointer" @click="() => router.push(`/user/${item.userId}`)" :src="item.author?.avatar" /></template>
                    </a-list-item-meta>
                    {{ item.articleContent }}
                  </a-list-item>
                </a-skeleton>
              </a-badge-ribbon>
              <a-list-item :id="item.id" v-else :key="item.id">
                <template #actions>
                <span v-if="item.collection" :style="{color : token.colorSuccess}"  style="cursor: pointer">
                  <component @click="toCollection(item)" :is="StarOutlined" style="margin-right: 8px" />
                  {{ item.collectionNum || 0 }}
                </span >
                  <span v-else style="cursor: pointer">
                    <component @click="toCollection(item)" :is="StarOutlined" style="margin-right: 8px" />
                    {{ item.collectionNum || 0 }}
                </span >

                  <span v-if="item.thumbs" :style="{color : token.colorSuccess}"  style="cursor: pointer">
                    <component  style="margin-right: 8px;"  @click="toThumbs(item)"  :is="LikeOutlined"  />
                    {{ item.thumbsNum || 0 }}
                </span>
                  <span v-else  style="cursor: pointer">
                    <component  style="margin-right: 8px;"  @click="toThumbs(item)"  :is="LikeOutlined"  />
                    {{ item.thumbsNum || 0 }}
                </span>

                  <span>
                    <component :is="MessageOutlined" style="margin-right: 8px" />
                    {{ item.articleCommentNum || 0 }}
                </span>

                  <span>
                    <component :is="MessageOutlined" style="margin-right: 8px" />
                    {{item.createTime}}
                </span>
                  <span v-if="user.id == item.userId">
                     <a-dropdown>
                        <a class="ant-dropdown-link" @click.prevent>
                          more
                          <DownOutlined />
                        </a>
                        <template #overlay>
                          <a-menu>
                            <a-menu-item >
                              <a-popconfirm
                                  title="删除后不可恢复，确定删除？"
                                  ok-text="是"
                                  cancel-text="否"
                                  @confirm="delArticle(item.id)">
                              <a href="#">删除</a>
                            </a-popconfirm>
                            </a-menu-item>
                            <a-menu-item @click="gotoAddArticle(item.id)">
                              <a href="javascript:;">编辑</a>
                            </a-menu-item>
                          </a-menu>
                        </template>
                      </a-dropdown>
                  </span>
                </template>
                <template v-if="item.articleCover && !isMobile.value" #extra>
                  <img
                      width="272"
                      height="150"
                      style="border-radius: 5px;cursor: pointer"
                      @click="gotoArticle(item.id)"
                      alt="logo"
                      :src="item.articleCover"
                  />
                </template>
                <a-list-item-meta description="">
                  <template #title>
                    <a @click="gotoArticle(item.id)" >{{ item.articleTitle }}</a>
                  </template>
                  <template #avatar><a-avatar  style="cursor: pointer" @click="() => router.push(`/user/${item.userId}`)" :src="item.author?.avatar" /></template>
                </a-list-item-meta>
                {{ item.articleContent }}
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>
    </a-row>
  </keep-alive>
</template>

<script lang="ts" setup>
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  PieChartOutlined,
  MailOutlined,
  DesktopOutlined,
  InboxOutlined,
  AppstoreOutlined,
  SmileOutlined,
  UserOutlined,
  EllipsisOutlined
} from '@ant-design/icons-vue';
//风格
import {message, theme} from 'ant-design-vue';
const {useToken} = theme;
const {token} = useToken();

import {getArticle,thumbs,collection,detArticle} from "@/api/article";
import {listType} from "@/api/type"
const typeList = reactive([
  {
    id: '',
    name: '全部',
  },
])
const {user} = useStore()
onMounted(() => {
  queryFrom.userId =  useRoute().params.userId
  init();
  listType({}).then(res => {
    typeList.push(...res.data)
  })
})
const init = async () => {
  loading.value = true;
  more.value = false;
  listData.value = tData.value.concat(
      [...new Array(pagination.pageSize)].map(() => ({ isTop: false, author: {}})),
  );
  const res = await getArticle(queryFrom,{
    pageSize : pagination.pageSize,
    pageNum : pagination.current
  });
  if(res.data.total > pagination.pageSize * pagination.current)
    more.value = true;
  const newData = tData.value.concat(res.data.rows);
  listData.value = newData
  tData.value = newData
  pagination.total = res.data.total
  loading.value = false;
  // nextTick(() => {
  //   // Resetting window's offsetTop so as to display react-virtualized demo underfloor.
  //   // In real scene, you can using public method of react-virtualized:
  //   // https://stackoverflow.com/questions/46700726/how-to-use-public-method-updateposition-of-react-virtualized
  //   window.dispatchEvent(new Event('resize'));
  // });
}
import { StarOutlined, FileOutlined, LikeOutlined, MessageOutlined } from '@ant-design/icons-vue';
import router from "@/router";
import {debounce, throttle} from "@/utils/common";
import {listType} from "@/api/type";
import useStore from "@/store";
const queryFrom = reactive({
  searchKey : "",
  typeId : "",
  seq:1,
  me:false,
  star:false,
  userId:""
})


const listData = ref([]);
const tData = ref([]);
const loading = ref<boolean>(false)
const pagination = reactive( {
  // onChange: (page: number) => {
  //   console.log(page);
  //   pagination.current = page
  //   init();
  // },
  current:1,
  pageSize:3,
  total:0
});
const more = ref<boolean>(false);
const isMobile = reactive({
  value: window.matchMedia('(max-width: 868px)').matches
});
// 监听窗口大小改变
window.addEventListener('resize', () => {
  isMobile.value = window.matchMedia('(max-width: 868px)').matches;
});
const gotoArticle = (id) => {
  router.push(`/article/${id}`)
}

const getArticlesDebounce = debounce(async () => {
  pagination.current = 1
  tData.value = []
  await init()
},500,{first : false, end : true})


watch(queryFrom, (newVal, oldVal) => {
  getArticlesDebounce()
})

const delArticle = (id) => {
  detArticle(id).then(() => {
    listData.value = listData.value.filter(item => item.id !=id)
    tData.value = listData.value
    message.success("删除成功！");
  })
}
const gotoAddArticle = (id) => {
  if(id != undefined && id != null)
    router.push({
      path:"/addArticle",
      query: {
        articleId : id
      }
    })
  else
    router.push("/addArticle")
}

const toThumbs = throttle((article) => {
  thumbs(article.id)
  if(article.thumbs == 1)
    article.thumbsNum -=1 ;
  else
    article.thumbsNum += 1;
    article.thumbs^=1;
})
const toCollection = throttle((article) => {
  collection(article.id)
  if(article.collection == 1)
    article.collectionNum -=1 ;
  else
    article.collectionNum += 1;
  article.collection^=1;
})

const onLoadMore = () => {
  pagination.current +=1;
  init();
};
</script>


<style lang="scss" scoped>

</style>
